package cn.dinkevin.xui.activity;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.tendcloud.tenddata.TCAgent;

import cn.dinkevin.xui.finder.ValueFinder;
import cn.dinkevin.xui.R;
import cn.dinkevin.xui.finder.ViewFinder;
import cn.dinkevin.xui.thread.ThreadExecutor;
import cn.dinkevin.xui.util.LogUtil;
import cn.dinkevin.xui.util.PermissionUtils;

/**
 * 抽象 Activity 基类
 * @author chengpengfei
 */
public abstract class AbstractActivity extends AppCompatActivity implements OnClickListener{

	/**
	 * 标题栏
	 */
	protected View view_head;
	
	/**
	 * 标题栏标题
	 */
	protected TextView txt_headTitle;						
	
	/**
	 * 标题栏左右按钮
	 */
	protected ImageView img_headLeft,img_headRight;	
	
	/**
	 * 标题栏右按钮
	 */
	protected TextView txt_headRight;
	public boolean permissionFlag =false;
	
	/**
	 * 根 view
	 */
	protected View view_root;
	
	protected ViewFinder viewFinder;
	protected LayoutInflater layoutInflater;
	protected boolean activityIsShow = false;	// 当前 Activity 是否显示

	protected static final int REQUEST_EXTERNAL_STORAGE = 1;
	protected static final String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE };

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);

		// 隐藏 ActionBar
		try {
			if(null!=getSupportActionBar())
				getSupportActionBar().hide();
		}catch (Exception e){}

		// 默认锁定 Activity 方向为竖直方向
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		layoutInflater = LayoutInflater.from(this);
		// 读取当前页面内容 ViewId，设置当前显示的内容 View
		int t_contentViewId = getContentLayout();
		if(t_contentViewId > 0)
		{
			// 将内容 view 添加到根 view
			view_root = layoutInflater.inflate(t_contentViewId, null);
			viewFinder = new ViewFinder(view_root);
			setContentView(view_root);
			
			// 初始化标题栏
			view_head = findView(R.id.view_head);
			txt_headTitle = findView(R.id.txt_head_title);
			img_headLeft = findView(R.id.img_head_left);
			img_headRight = findView(R.id.img_head_right);
			txt_headRight = findView(R.id.txt_head_right);
			
			// 清空标题
			if(txt_headTitle != null)
				txt_headTitle.setText("");
			
			// 默认的返回
			if(img_headLeft != null)
				img_headLeft.setOnClickListener(this);
		}
		permissionFlag =true;

		TCAgent.onPageStart(this, LogUtil.getTag(this));
	}

	@Override
	protected void onStop() {
		super.onStop();
		permissionFlag =true;
	}

	/**
	 * 请求高版本系统的文件读写权限
	 */
	protected void requestStoragePermission(){
		ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
	}

	/**
	 * 检测设备上文件读写权限
	 * @return true -> 已经获取到文件读写权限
     */
	protected boolean checkStoragePermission(){
		if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1){
			int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
			if (permission != PackageManager.PERMISSION_GRANTED) {
				requestStoragePermission();
				return false;
			}
		}
		return true;
	}

	private MaterialDialog mMaterialDialog;

	/**
	 * 打开等待对话框
	 *
	 * @param isCancelable 是否可以取消
     */
	protected void showWaitingDialog(boolean isCancelable){
		closeWaitingDialog();
		if (this==null) return;
		mMaterialDialog = new MaterialDialog.Builder(this)
				.content(R.string.xui_loading)
				.progress(true, 0)
				.widgetColor(ValueFinder.getColor(R.color.xui_progress_green))
				.progressIndeterminateStyle(false)
				.cancelable(isCancelable)
				.show();
	}


	/**
	 * 弹出进度对话框
	 * @param isCancelable 是否可以取消
	 * @param max	最大值
	 */
	public void showWaitingDialog(boolean isCancelable, int max){
		closeWaitingDialog();
		mMaterialDialog = new MaterialDialog.Builder(this)
				.content(R.string.xui_loading)
				.progress(true, max)
				.widgetColor(ValueFinder.getColor(R.color.xui_progress_green))
				.progressIndeterminateStyle(false)
				.cancelable(isCancelable)
				.show();
	}


	/**
	 * 更新等待对话框提示文字
	 * @param content
	 */
	public void updateWaitingDialogTip(final String content){
		if(null == mMaterialDialog) return;
		mMaterialDialog.setContent(content);
	}


	/**
	 * 关闭对话框
	 */
	public void closeWaitingDialog(){

		ThreadExecutor.main(new Runnable() {

			@Override
			public void run() {

				if(null == mMaterialDialog) return;

				try{
					mMaterialDialog.cancel();
					mMaterialDialog.dismiss();
					mMaterialDialog = null;
				}catch (Exception e){
					LogUtil.e("dialog close error", Log.getStackTraceString(e));
				}
			}
		});
	}

	/**
	 * 退出全屏模式
	 */
	protected void exitFullScreen(){
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setAttributes(params);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

		if(viewFinder != null && viewFinder.getRootView() != null)
			viewFinder.getRootView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
	}

	/**
	 * 进入全屏模式
	 */
	protected void enterFullScreen(){
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		getWindow().setAttributes(params);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

		if(viewFinder != null && viewFinder.getRootView() != null)
			viewFinder.getRootView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
	}
	
	/**
	 * 获取当前内容页面资源Id
	 * @return
	 */
	protected abstract int getContentLayout();
	
	/**
	 * 在 {@link #view_root} 中查找资源 Id 对应的 View
	 * @param viewResId 资源 Id
	 * @return 
	 */
	protected <T extends View> T findView(int viewResId){
		return viewFinder.findViewById(viewResId);
	}

	/**
	 * 设置当前页面标题
	 */
	@Override
	public void setTitle(CharSequence title) {
		if(txt_headTitle != null)
			txt_headTitle.setText(title);
	}

	/**
	 * 设置当前页面标题
	 */
	@Override
	public void setTitle(int titleId) {
		if(txt_headTitle != null)
			txt_headTitle.setText(titleId);
	}
	
	/**
	 * 设置输入框的最大输入长度
	 * @param edt
	 * @param maxLength
	 */
	protected void setMaxInputLength(EditText edt,int maxLength){
		if(edt == null || maxLength < 1) return;
		edt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
	}

	/**
	 * 获取指定 EditText 中的内容（去掉两头的空格）
	 * @param edt
	 * @return
     */
	protected String getTextTrim(EditText edt){
		return edt.getText().toString().trim();
	}

	@Override
	public void onClick(View v) {
		if(v == img_headLeft){
			finish();
		}
	}

	/**
	 * 载入指定资源的布局
	 * @param layoutResId
	 * @return
     */
	protected View inflate(int layoutResId){
		return layoutInflater.inflate(layoutResId,null);
	}

	@Override
	protected void onResume() {
		super.onResume();
		activityIsShow = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		permissionFlag =false;
		activityIsShow = false;
	}

	/**
	 * 当前 Activity 是否为可见
	 * @return
     */
	public boolean activityIsShow(){
		return activityIsShow;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeWaitingDialog();
		TCAgent.onPageEnd(this, LogUtil.getTag(this));
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
	}

	public PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
		@Override
		public void onPermissionGranted(int requestCode) {
            if (getmPermissions!=null)
                getmPermissions.getrequestCode(requestCode);
		}
	};

	public interface getmPermission{
        void getrequestCode(int requestCode);
    }

    protected getmPermission getmPermissions;

    public void setBackPermission(getmPermission getmPermission){
            this.getmPermissions=getmPermission;
    }


	public void onPermissionDenied() {
		finish();
	}
}
